Audio Player

The AVPlayer API allows you to play audio or video with various customizable options. Below is a detailed guide on how to use this API effectively, with notes on best practices and potential issues.


Getting Started

To use AVPlayer, create an instance and set the media source using setSource(). Configure the desired playback options like volume or rate, and start playback with play().

1const player = new AVPlayer()
2
3// Set the media source (local or remote)
4if (player.setSource("https://example.com/audio.mp3")) {
5    player.onReadyToPlay = () => {
6        player.play()
7    }
8    player.onEnded = () => {
9        console.log("Playback finished.")
10    }
11} else {
12    console.error("Failed to set media source.")
13}

API Reference

Properties

  • volume: number

    • Controls the playback volume, ranging from 0.0 (muted) to 1.0 (full volume).
    • Example:
      1player.volume = 0.5 // Set to 50% volume
  • duration: DurationInSeconds

    • The total duration of the media. Will be 0 until the media is ready.
    • Example:
      1console.log(`Media duration: ${player.duration} seconds`)
  • currentTime: DurationInSeconds

    • The current playback position. Can also be set to seek to a specific time.
    • Example:
      1player.currentTime = 30 // Seek to 30 seconds
  • rate: number

    • Controls playback speed. 1.0 is normal speed; higher values increase speed.
    • Example:
      1player.rate = 1.5 // Play 1.5x faster
  • timeControlStatus: TimeControlStatus

    • Indicates playback state (e.g., playing, paused, waiting).
  • numberOfLoops: number

    • Sets how many times the media should loop. 0 for no loops, -1 for infinite loops.
    • Example:
      1player.numberOfLoops = -1 // Loop indefinitely

Methods

  • setSource(filePathOrURL: string): boolean

    • Sets the media source. Accepts a local file path or a remote URL.
    • Returns true on success.
  • play(): boolean

    • Starts playback. Returns true if successful.
  • pause()

    • Pauses playback.
  • stop()

    • Stops playback and resets to the beginning.
  • dispose()

    • Releases all resources. Must be called when the player is no longer needed.

Callbacks

  • onReadyToPlay?: () => void

    • Called when the media is ready to play.
  • onTimeControlStatusChanged?: (status: TimeControlStatus) => void

    • Called when the playback status changes.
  • onEnded?: () => void

    • Called when playback ends.
  • onError?: (message: string) => void

    • Called when an error occurs.

Handling Audio Sessions

The AVPlayer API relies on the system's shared audio session. Here are key considerations:

  1. Audio Session Interruption

    • Register an interruption listener using SharedAudioSession.addInterruptionListener to handle interruptions such as incoming calls.
    • Example:
      1SharedAudioSession.addInterruptionListener((type) => {
      2    if (type === 'began') {
      3        player.pause()
      4    } else if (type === 'ended') {
      5        player.play()
      6    }
      7})
  2. Category and Options

    • Set the appropriate audio session category and options based on the use case.
    • Example:
      1await SharedAudioSession.setCategory('playback', ['mixWithOthers'])
  3. Activation

    • Activate the audio session before playback.
    • Example:
      1await SharedAudioSession.setActive(true)

Common Use Cases

Play Remote Audio

1player.setSource("https://example.com/audio.mp3")
2player.onReadyToPlay = () => {
3    player.play()
4}

Play Local Audio

1player.setSource("/path/to/local/audio.mp3")
2player.play()

Handle Playback Events

1player.onEnded = () => {
2    console.log("Playback finished.")
3}
4player.onError = (message) => {
5    console.error("Playback error:", message)
6}

Loop Playback

1player.numberOfLoops = 3 // Loop 3 times
2player.play()

Best Practices

  1. Resource Management

    • Always call dispose() when the player is no longer needed.
  2. Error Handling

    • Implement onError to handle playback issues, such as network failures.
  3. Audio Session Configuration

    • Configure the audio session category and options appropriately for your app's behavior.
  4. Interruption Management

    • Use interruption listeners to pause and resume playback gracefully.
  5. Optimize for User Experience

    • Provide UI feedback for loading and playback states using onReadyToPlay and onTimeControlStatusChanged callbacks.

Full Example

Here is a complete example showcasing how to use the AVPlayer API:

1// Create an instance of AVPlayer
2const player = new AVPlayer()
3
4// Configure audio session
5await SharedAudioSession.setCategory('playback', ['mixWithOthers'])
6await SharedAudioSession.setActive(true)
7
8// Set the media source
9if (player.setSource("https://example.com/audio.mp3")) {
10    // Register events
11    player.onReadyToPlay = () => {
12        console.log("Media is ready to play")
13        player.play()
14    }
15
16    player.onEnded = () => {
17        console.log("Playback finished")
18        player.dispose()
19    }
20
21    player.onError = (message) => {
22        console.error("Playback error:", message)
23        player.dispose()
24    }
25} else {
26    console.error("Failed to set media source")
27}
28
29// Handle interruptions
30SharedAudioSession.addInterruptionListener((type) => {
31    if (type === 'began') {
32        player.pause()
33    } else if (type === 'ended') {
34        player.play()
35    }
36})